// pages/login/login.js
import {
  debounce
} from 'miniprogram-licia'
import {
  reqLogin,
  getUserInfo
} from '../../api/user'
import {
  toast
} from '../../utils/extendApi'
import {
  setStorage
} from '../../utils/storage'
import {
  ComponentWithStore
} from "mobx-miniprogram-bindings"
import {
  userStore
} from '../../store/userStore'
ComponentWithStore({
  storeBindings: {
    store: userStore,
    fields: ['token'],
    actions: ['setToken', 'setUserInfo']
  },
  methods: {
    login: debounce(function () {
      wx.login({
        success: async ({
          code
        }) => {
          if (code) {
            const {
              data: {
                token
              }
            } = await reqLogin(code)
            setStorage('token', token)
            this.setToken(token)
            this.getUserInfo()
            toast({
              title: '登录成功!',
              icon: 'success'
            })
            wx.navigateBack()
          } else {
            toast({
              title: '授权失败,请重新操作'
            })
          }
        },
      })
    }, 500),
    async getUserInfo() {
      const {
        data
      } = await getUserInfo()
      setStorage('userInfo', data)
      this.setUserInfo(data)
    }
  }

})